const Koa = require('koa');
const Router = require('koa-router');
const cors = require('@koa/cors');
const bodyParser = require('koa-bodyparser');
const path = require('path');
const serve = require('koa-static');
const mount = require('koa-mount');
const publicRoutes = require('./routes/public');
const readerRoutes = require('./routes/reader');
const adminRoutes = require('./routes/admin');
const authMiddleware = require('./middleware/auth');
const errorMiddleware = require('./middleware/error');
const sequelize = require('./config/db');

const app = new Koa();

// 静态文件服务
const filesPath = path.join(__dirname, '../files');
app.use(mount('/files', serve(filesPath)));

// Middleware
app.use(cors());
app.use(errorMiddleware);
app.use(bodyParser());

const router = new Router();
router.use('/public', publicRoutes.routes());
router.use('/reader', readerRoutes.routes());
router.use('/admin', adminRoutes.routes());

app.use(router.routes());
app.use(router.allowedMethods());

const PORT = process.env.PORT || 3001;

sequelize.sync().then(() => {
  app.listen(PORT, () => {
    console.log(`Server is running on port ${PORT}`);
  });
}).catch(err => {
  console.error('Unable to connect to the database:', err);
});